package org.atovio.coolexam.controller.student;

import org.atovio.coolexam.common.Result;
import org.atovio.coolexam.entity.*;
import org.atovio.coolexam.service.*;
import org.atovio.coolexam.viewmodel.student.exam.CustomerAnswerItemVM;
import org.atovio.coolexam.viewmodel.student.exam.QuestionItemVM;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 实现考试功能的主要控制器
 */
@RestController
@RequestMapping("/student/exam")
public class ExamController {

    private final QuestionService questionService;
    private final QuestionOptionsService questionOptionsService;
    private final ExamPaperAnswerService examPaperAnswerService;
    private final ExamPaperQuestionService examPaperQuestionService;
    private final ExamPaperQuestionCustomerAnswerService examPaperQuestionCustomerAnswerService;

    @Autowired
    public ExamController(QuestionService questionService, QuestionOptionsService questionOptionsService,
                          ExamPaperAnswerService examPaperAnswerService, ExamPaperQuestionService examPaperQuestionService,
                          ExamPaperQuestionCustomerAnswerService examPaperQuestionCustomerAnswerService) {
        this.questionService = questionService;
        this.questionOptionsService = questionOptionsService;
        this.examPaperAnswerService = examPaperAnswerService;
        this.examPaperQuestionService = examPaperQuestionService;
        this.examPaperQuestionCustomerAnswerService = examPaperQuestionCustomerAnswerService;
    }

    /**
     * 考试每次修改答题答案都会调用此方法，对答题答案进行实时修改
     * @param caiVM 答题答案条目
     * @return 响应结果
     */
    @PostMapping("/answer/items")
    public Result submitItem(@RequestBody CustomerAnswerItemVM caiVM) {
        Map<String, Object> criteria = new HashMap<>();
        criteria.put("questionId", caiVM.getQuestionId());
        criteria.put("examPaperId", caiVM.getExamPaperId());
        criteria.put("createUserId", caiVM.getUserId());

        List<ExamPaperQuestionCustomerAnswer> answerItems = examPaperQuestionCustomerAnswerService.getSelective(criteria);
        ExamPaperQuestionCustomerAnswer answer = answerItems.get(0);
        answer.setAnswer(caiVM.getCustomerAnswer());

        examPaperQuestionCustomerAnswerService.modifyAnswerById(answer.getId(), answer.getAnswer());
        // 如果为客观题，自动判分
        Question question = questionService.getById(caiVM.getQuestionId());
        if (question.getQuestionType() != 5) {
            if (question.getCorrectAnswer().equals(answer.getAnswer())) {
                examPaperQuestionCustomerAnswerService.modifyCustomerScoreById(answer.getId(), question.getScore());
            } else {
                examPaperQuestionCustomerAnswerService.modifyCustomerScoreById(answer.getId(), 0);
            }
        }

        return Result.success();
    }

    /**
     * 考试开始考试前的答卷初始化，会为每道题目赋上初始0分
     * @param initialData 初始化数据
     * @return 响应结果
     */
    @PostMapping("/first")
    public Result initCustomerAnswerPaper(@RequestBody Map<String, Object> initialData) {
        Integer examPaperId = (Integer) initialData.get("examPaperId");
        // 获取试卷的所有题目id
        List<ExamPaperQuestion> examPaperQuestions = examPaperQuestionService.getByExamPaperId(examPaperId);
        Integer userId = (Integer) initialData.get("userId");

        // 初始化答卷
        ExamPaperAnswer examPaperAnswer = new ExamPaperAnswer();
        examPaperAnswer.setExamPaperId(examPaperId);
        examPaperAnswer.setCreateUserId(userId);
        examPaperAnswer.setStatus(1);
        ExamPaperAnswer dbExamPaperAnswer = examPaperAnswerService.add(examPaperAnswer);

        // 初始化用户答案
        examPaperQuestions.forEach(epq -> {
            ExamPaperQuestionCustomerAnswer customerAnswer = new ExamPaperQuestionCustomerAnswer();
            customerAnswer.setExamPaperId(examPaperId);
            customerAnswer.setQuestionId(epq.getQuestionId());
            customerAnswer.setExamPaperAnswerId(dbExamPaperAnswer.getId());
            customerAnswer.setCreateUserId(userId);
            customerAnswer.setCustomerScore(0);

            examPaperQuestionCustomerAnswerService.add(customerAnswer);
        });
        return Result.success();
    }

    /**
     * 获取试卷的题目
     * @param examPaperId 试卷id
     * @return 响应结果
     */
    @GetMapping("/items")
    public Result getExamPaperItem(@RequestParam Integer examPaperId) {
        List<QuestionItemVM> questionItemVMs = new ArrayList<>();
        List<ExamPaperQuestion> examPaperQuestions = examPaperQuestionService.getByExamPaperId(examPaperId);
        examPaperQuestions.forEach(eq -> {
            QuestionItemVM vm = new QuestionItemVM();
            Question question = questionService.getById(eq.getQuestionId());
            List<QuestionOptions> questionOptions = questionOptionsService.getByQuestionId(question.getId());

            vm.setQuestion(question);
            vm.setQuestionOptions(questionOptions);

            questionItemVMs.add(vm);
        });
        return Result.success(questionItemVMs);
    }
}
